package a归并;

public class 合并K个升序链表归并 {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    class Solution {
        public ListNode mergeKLists(ListNode[] lists) {
            return merge(lists, 0, lists.length - 1);
        }

        public ListNode merge(ListNode[] lists, int l, int r) {
            // 处理边界
            if (l == r) {
                return lists[l];
            }
            if (l > r) {
                return null;
            }

            int mid = l + ((r - l) >> 1);
            //左子树
            ListNode left = merge(lists, l, mid);
            //右子树
            ListNode right = merge(lists, mid + 1, r);
            //合并
            return hebing(left, right);
        }

        public ListNode hebing(ListNode left, ListNode right) {
            //创建一个虚拟节点
            ListNode head = new ListNode(0);
            ListNode tmp = head;
            while (left != null && right != null) {
                if (left.val <= right.val) {
                    tmp.next = left;
                    left = left.next;
                } else {
                    tmp.next = right;
                    right = right.next;
                }
                tmp = tmp.next;
            }
            tmp.next = left != null ? left : right;
            return head.next;
        }
    }
}
